<template>
  <!-- 搜索表单 -->
  <el-form :model="page" :inline="true" class="mb-4" style="width: 100%">
    <el-form-item label="转移单编号">
      <el-input v-model="page.TransferOrderNumber" placeholder="请输入转移单编号"></el-input>
    </el-form-item>
    <el-form-item label="转移单名称">
      <el-input v-model="page.TransferOrderName" placeholder="请输入转移单名称"></el-input>
    </el-form-item>
    <el-form-item label="转移单类型">
      <el-select v-model="page.TransferOrderType" style="width: 180px;">
        <el-option label="外部转移" value="外部转移" />
        <el-option label="内部转移" value="内部转移" />
      </el-select>
    </el-form-item>
    <el-button type="primary" @click="ShowTBS">搜索</el-button>
    <el-button @click="resetForm">重置</el-button>
  </el-form>
  <div>
    <el-button type="primary" plain @click="dialogFormVisible = true">
      + 新增
    </el-button>
    <el-button type="primary" plain @click="TZ()">
      报表
    </el-button>
  </div>

  <el-table :data="tableData" style="width: 100%">
    <el-table-column fixed prop="transferOrderNumber" label="转移单编号" width="150" />
    <el-table-column prop="transferOrderName" label="转移单名称" width="120" />
    <el-table-column prop="transferOrderType" label="转移单类型" width="120" />
    <el-table-column prop="isDelivery" label="是否配送" width="120">
      <template #default="{ row }">
        <el-tag type="danger" v-if="!row.isDelivery">否</el-tag>
        <el-tag type="success" v-if="row.isDelivery">是</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="transferDate" label="转移日期" width="120">
      <template #default="{ row }">
        {{ row.transferDate.split('T')[0] }} <!-- 格式化日期去掉时间 -->
      </template>
    </el-table-column>
    <el-table-column prop="transferOrderzt" label="单据状态" width="120">
      <template #default="{ row }">
        <el-tag v-if="!row.transferOrderzt">已完成</el-tag>
        <el-tag v-if="row.transferOrderzt">草稿</el-tag>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="script">
        <!-- 传递当前行数据到修改方法 -->
        <el-button link type="primary" plain @click="UpdateXG(script.row)">
         修改
        </el-button>
        <el-button link type="danger" size="small" @click="handleDelete(script.row.transferOrderId)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 添加对话框 -->
  <el-dialog v-model="dialogFormVisible" title="添加转移单" width="1100">
    <el-form :model="ruleForms" label-width="90px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="*转移单编号">
            <el-row>
              <el-col span="18">
                <el-input
                  v-model="ruleForms.transferOrderNumber"
                  placeholder="请输入转移单编号"
                  :disabled="ruleForms.autoGenerate"
                />
              </el-col>
              <el-col span="6">
                <el-switch
                  v-model="ruleForms.autoGenerate"
                  inactive-text=""
                  active-text="自动生成"
                  label="自动生成"
                />
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="转移单类型">
            <el-radio-group v-model="ruleForms.transferOrderType">
              <el-radio label="内部转移">内部转移</el-radio>
              <el-radio label="外部转移">外部转移</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="*转移单名称">
            <el-input
              v-model="ruleForms.transferOrderName"
              placeholder="请输入转移单名称"
            />
          </el-form-item>
          <el-form-item label="*转移日期">
            <el-date-picker
              v-model="ruleForms.transferDate"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
          <!-- 仅外部转移显示是否配送 -->
          <el-form-item label="是否配送" v-if="ruleForms.transferOrderType === '外部转移'">
            <el-switch
              v-model="ruleForms.isDelivery"
              active-text="是"
              inactive-text="否"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 仅外部转移且配送时显示配送信息 -->
      <el-row v-if="ruleForms.isDelivery && ruleForms.transferOrderType === '外部转移'">
        <el-col :span="6">
          <el-form-item label="收货人">
            <el-input
              v-model="ruleForms.consignee"
              placeholder="请输入收货人"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系方式">
            <el-input
              v-model="ruleForms.contactInformation"
              placeholder="请输入联系方式"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="承运商">
            <el-input
              v-model="ruleForms.carrier"
              placeholder="请输入承运商"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="运输单号">
            <el-input
              v-model="ruleForms.transportOrderNumber"
              placeholder="请输入运输单号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目的地">
            <el-input
              v-model="ruleForms.destination"
              placeholder="请输入目的地"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注">
        <el-input
          v-model="ruleForms.remarks"
          type="textarea"
          placeholder="请输入内容"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 修改对话框 -->
  <el-dialog v-model="dialogFormVisibles" title="修改转移单" width="1100">
    <el-form :model="ruleForm" label-width="90px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="*转移单编号">
            <el-row>
              <el-col span="18">
                <el-input
                  v-model="ruleForm.transferOrderNumber"
                  placeholder="请输入转移单编号"
                  :disabled="ruleForm.autoGenerate"
                />
              </el-col>
              <el-col span="6">
                <el-switch
                  v-model="ruleForm.autoGenerate"
                  inactive-text=""
                  active-text="自动生成"
                  label="自动生成"
                />
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="转移单类型">
            <el-radio-group v-model="ruleForm.transferOrderType">
              <el-radio label="内部转移">内部转移</el-radio>
              <el-radio label="外部转移">外部转移</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="*转移单名称">
            <el-input
              v-model="ruleForm.transferOrderName"
              placeholder="请输入转移单名称"
            />
          </el-form-item>
          <el-form-item label="*转移日期">
            <el-date-picker
              v-model="ruleForm.transferDate"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
          <!-- 仅外部转移显示是否配送 -->
          <el-form-item label="是否配送" v-if="ruleForm.transferOrderType === '外部转移'">
            <el-switch
              v-model="ruleForm.isDelivery"
              active-text="是"
              inactive-text="否"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 仅外部转移且配送时显示配送信息 -->
      <el-row v-if="ruleForm.isDelivery && ruleForm.transferOrderType === '外部转移'">
        <el-col :span="6">
          <el-form-item label="收货人">
            <el-input
              v-model="ruleForm.consignee"
              placeholder="请输入收货人"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系方式">
            <el-input
              v-model="ruleForm.contactInformation"
              placeholder="请输入联系方式"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="承运商">
            <el-input
              v-model="ruleForm.carrier"
              placeholder="请输入承运商"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="运输单号">
            <el-input
              v-model="ruleForm.transportOrderNumber"
              placeholder="请输入运输单号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目的地">
            <el-input
              v-model="ruleForm.destination"
              placeholder="请输入目的地"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注">
        <el-input
          v-model="ruleForm.remarks"
          type="textarea"
          placeholder="请输入内容"
        />
      </el-form-item>
    </el-form>
    <!-- 物料信息区域 -->
    <div class="工序-container">
      <div class="工序-header">
        <span>○ 物料信息</span>
        <div class="operation-buttons">
          <el-button type="primary" size="small" @click="handleAddMaterial(ruleForm)">+ 新增</el-button>
          <el-button type="danger" size="small" @click="handleDeleteMaterial(ruleForm)">删除</el-button>
        </div>
      </div>
      <el-table :data="ruleForm.materials" style="width: 100%; margin-top: 10px;">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="productMaterial" label="物资" width="120" />
        <el-table-column prop="productMaterialName" label="物资名称" width="120" />
        <el-table-column prop="specificationModel" label="规格型号" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="transferQuantity" label="转移数量" width="100"/>
        <el-table-column prop="batchNumber" label="批次号" width="120" />
        <el-table-column prop="outWarehouse" label="移出仓库" width="120" />
        <el-table-column label="操作" min-width="180">
          <template #default="scope">
            <el-link type="success" size="small" @click="handleEditMaterial(scope.row, ruleForm)">编辑</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisibles = false">取消</el-button>
        <el-button type="primary" @click="XG()">确认</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 分页 -->
  <el-pagination
      v-model:current-page="page.Index"
      v-model:page-size="page.Size"
      :page-sizes="[5, 10, 15, 20]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.TotalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      prev-text="上一页"
      next-text="下一页"
    />
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import type { ComponentSize } from 'element-plus'
import router from '@/router';
const apiUrl = import.meta.env.VITE_APP_API_URL;

const currentPage1 = ref(5)
const currentPage2 = ref(5)
const currentPage3 = ref(5)
const currentPage4 = ref(4)
const pageSize2 = ref(100)
const pageSize3 = ref(100)
const pageSize4 = ref(100)
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)

const dialogFormVisible = ref(false);
const dialogFormVisibles = ref(false);

// 表单数据模型
const ruleForms = reactive({
  transferOrderId: 0,
  transferOrderNumber: '',
  autoGenerate: true, // 自动生成开关（默认开启）
  transferOrderName: '',
  transferOrderType: '', // 转移类型（内部/外部）
  transferDate: new Date(), // 转移日期（默认当前日期）
  isDelivery: false, // 是否配送（仅外部转移显示）
  consignee: '', // 收货人（配送相关）
  contactInformation: '', // 联系方式
  carrier: '', // 承运商
  transportOrderNumber: '', // 运输单号
  destination: '', // 目的地
  remarks: '', // 备注
  transferOrderzt: true, // 单据状态（草稿/已完成）
  isDelete: true, // 是否删除
  materials: [] // 物料信息数组
});

const ruleForm = reactive({
  transferOrderId: 0,
  transferOrderNumber: '',
  autoGenerate: true, // 自动生成开关（默认开启）
  transferOrderName: '',
  transferOrderType: '', // 转移类型（内部/外部）
  transferDate: new Date(), // 转移日期（默认当前日期）
  isDelivery: false, // 是否配送（仅外部转移显示）
  consignee: '', // 收货人（配送相关）
  contactInformation: '', // 联系方式
  carrier: '', // 承运商
  transportOrderNumber: '', // 运输单号
  destination: '', // 目的地
  remarks: '', // 备注
  transferOrderzt: true, // 单据状态（草稿/已完成）
  isDelete: true, // 是否删除
  materials: [] // 物料信息数组
});

// 监听自动生成开关，生成带时分秒的编号
watch(
  () => ruleForm.autoGenerate,
  (newVal) => {
    if (newVal) {
      ruleForm.transferOrderNumber = generateTransferOrderNumber();
    } else {
      ruleForm.transferOrderNumber = '';
    }
  }
);

// 生成带时分秒的转移单编号（格式：YYYYMMDDHHmmss）
const generateTransferOrderNumber = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  return `${year}${month}${day}${hour}${minute}${second}`;
};

watch(
  () => ruleForms.autoGenerate,
  (newVal) => {
    if (newVal) {
      ruleForms.transferOrderNumber = generateTransferOrderNumber();
    } else {
      ruleForms.transferOrderNumber = '';
    }
  }
);

// 搜索表单数据
const page = reactive({
  Index: 1,
  Size: 15,
  TotalCount: 0,
  PageCount: 0,
  TransferOrderNumber: '',
  TransferOrderName: '',
  TransferOrderType: ''
});

// 重置搜索表单
const resetForm = () => {
  page.TransferOrderNumber = '';
  page.TransferOrderName = '';
  page.TransferOrderType = '';
};

// 添加/修改提交
const handleConfirm = () => {
  axios.post(apiUrl+'/T6/setting/AddTB', ruleForms)
    .then(res => {
      if (res.data.code === 100) {
        ElMessage.success('添加成功');
        dialogFormVisible.value = false;
        ShowTBS();
      } else {
        ElMessage.error('添加失败');
      }
    });
};

const XG = () => {
  axios.put(apiUrl+'/T6/setting/UpdateTB', ruleForm)
    .then(res => {
      if (res.data.code === 206) {
        ElMessage.success('修改成功');
        dialogFormVisibles.value = false;
        ShowTBS();
      } else {
        ElMessage.error('修改失败');
      }
    });
};

const TZ = () => {
    window.location.href = 'http://localhost:8075/webroot/decision/view/duchamp?viewlet=%25E7%25AC%25AC%25E4%25B8%2580%25E5%25BC%25A0FVS%25E6%25A8%25A1%25E6%259D%25BF.fvs&page_number=2';
};

// 编辑记录反填
const UpdateXG = async (row: any) => {
  Object.assign(ruleForm, {
    transferOrderId: row.transferOrderId,
    transferOrderNumber: row.transferOrderNumber,
    autoGenerate: false, // 编辑时禁用自动生成（允许修改编号）
    transferOrderName: row.transferOrderName,
    transferOrderType: row.transferOrderType,
    transferDate: new Date(row.transferDate), // 转换为Date对象用于日期选择器
    isDelivery: row.isDelivery,
    consignee: row.consignee,
    contactInformation: row.contactInformation,
    carrier: row.carrier,
    transportOrderNumber: row.transportOrderNumber,
    destination: row.destination,
    remarks: row.remarks,
    transferOrderzt: row.transferOrderzt,
    isDelete: row.isDelete
  });

  try {
    const response = await axios.get(apiUrl+'/T5/Setting/ShowTBS', {
      params: { inventoryTransferId: row.transferOrderId }
    });
    ruleForm.materials = response.data.data;
  } catch (error) {
    console.error('获取物料信息失败:', error);
    ElMessage.error('获取物料信息失败');
  }

  dialogFormVisibles.value = true; // 显示编辑对话框
};

// 初始化加载数据
onMounted(() => {
  ShowTBS();
});

// 获取数据列表
const ShowTBS = () => {
  axios.get(apiUrl+'/T5/Setting/ShowTB', { params: page })
    .then(res => {
      tableData.value = res.data.data;
      page.TotalCount = res.data.totalCount;
      page.PageCount = res.data.pageCount;
    });
};

const handleSizeChange = (val: number) => {
  page.Size = val; 
  ShowTBS();
};

const handleCurrentChange = (val: number) => {
  page.Index = val; 
  ShowTBS();
};

// 删除记录
const handleDelete = (transferOrderId: number) => {
  axios.put(apiUrl+'/T6/setting/DelTB', { transferOrderId })
    .then(res => {
      if (res.data.code === 204) {
        ElMessage.success('删除成功');
        ShowTBS();
      } else {
        ElMessage.error('删除失败');
      }
    });
};

// 表格数据
const tableData = ref([]);

// 物料相关数据
const isAddingMaterial = ref(false);
const newMaterialForm = reactive({
  materialCode: '',
  materialName: '',
  specificationModel: '',
  unit: '',
  transferQuantity: 0,
  batchNumber: '',
  outWarehouse: ''
});

const handleAddMaterial = (form) => {
  isAddingMaterial.value = true;
  Object.assign(newMaterialForm, {
    materialCode: '',
    materialName: '',
    specificationModel: '',
    unit: '',
    transferQuantity: 0,
    batchNumber: '',
    outWarehouse: ''
  });
};

const submitAddMaterial = (form) => {
  form.materials.push({ ...newMaterialForm });
  isAddingMaterial.value = false;
};

const cancelAddMaterial = () => {
  isAddingMaterial.value = false;
  Object.assign(newMaterialForm, {
    materialCode: '',
    materialName: '',
    specificationModel: '',
    unit: '',
    transferQuantity: 0,
    batchNumber: '',
    outWarehouse: ''
  });
};

const handleEditMaterial = (row, form) => {
  // 编辑逻辑，可在此处添加axios调用更新物料接口
  console.log('编辑物料:', row);
};

const handleDeleteMaterial = (form) => {
  form.materials = form.materials.filter((_, index) => !form.$indexes[index]);
};
</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
.工序-container {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 4px;
}
.工序-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.operation-buttons {
  display: flex;
  gap: 8px;
}
</style>    